package com.haochang.chunkvod.app.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.text.TextUtils;

public class HashUtils
{
	private final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private String toHexString(byte[] b)
	{
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++)
		{
			sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	/**
	 * Hash 文件的 MD5 值
	 * @param file
	 * @return
	 */
	public String md5File(File file)
	{
		String returnValue = "";
		if (file != null && file.exists() && !file.isDirectory())
		{
			InputStream fis;
			final int iBufferSize = 1024 * 10;
			byte[] buffer = new byte[iBufferSize];
			int numRead = 0;
			MessageDigest md5;
			try
			{
				fis = new FileInputStream(file);
				md5 = MessageDigest.getInstance("MD5");
				while ((numRead = fis.read(buffer)) > 0)
				{
					md5.update(buffer, 0, numRead);
				}
				fis.close();
				returnValue = toHexString(md5.digest());
			} catch (Exception e)
			{
				returnValue = "";
			}
		}
		return returnValue;
	}

	/**
	 * Hash 文件的 MD5 值
	 * @param filePath 文件路径
	 * @return 文件不存在.返回空白字符串
	 */
	public String md5File(String filePath)
	{
		String returnValue = "";
		if (!TextUtils.isEmpty(filePath))
		{
			File file = null;
			try
			{
				file = new File(filePath);
			} catch (Exception ex)
			{
				file = null;
			} finally
			{
				if (file != null)
					returnValue = this.md5File(file);
			}
		}
		return returnValue;
	}

	/**
	 * Hash 字符串的 MD5 值
	 * @param value
	 * @return
	 */
	public String md5String(String value)
	{
		String returnValue = "";
		if (value != null)
		{
			byte[] input = value.getBytes();
			try
			{
				MessageDigest md5;
				md5 = MessageDigest.getInstance("MD5");
				md5.update(input);
				returnValue = toHexString(md5.digest());
			} catch (NoSuchAlgorithmException e)
			{
				returnValue = "";
			}
		}

		return returnValue;
	}

	/**
	 * 文件md5校验，检查目标文件的MD5是否和传入的字符串相同
	 *
	 * @param md5 目标md5码
	 * @param file 目标文件
	 * @return
	 */
	public boolean md5FileCheck(String md5, File file)
	{
		if (TextUtils.isEmpty(md5) || file == null || !file.exists())
			return false;
		
		String sourceMd5 = md5File(file);
		return !TextUtils.isEmpty(sourceMd5) && sourceMd5.equals(md5);
	}
}
